package com.auxgroup.hr.front.service.process.impl;

import com.alibaba.fastjson.JSON;
import com.auxgroup.hr.front.commons.config.BusinessConfig;
import com.auxgroup.hr.front.commons.enums.WfTypeEnum;
import com.auxgroup.hr.front.commons.exception.ValidationException;
import com.auxgroup.hr.front.commons.utils.DateUtils;
import com.auxgroup.hr.front.commons.utils.ObjectFieldUtils;
import com.auxgroup.hr.front.commons.vo.UserDTO;
import com.auxgroup.hr.front.dao.domain.*;
import com.auxgroup.hr.front.dao.repository.PsCWfEmpVwRepository;
import com.auxgroup.hr.front.dao.repository.PsCWfWkotDtlRepository;
import com.auxgroup.hr.front.dao.repository.PsCWfWkotHdrRepository;
import com.auxgroup.hr.front.dozer.IObjectMapper;
import com.auxgroup.hr.front.hrverify.AuxCheckRequest;
import com.auxgroup.hr.front.hrverify.AuxCheckResponse;
import com.auxgroup.hr.front.service.comm.SysDictService;
import com.auxgroup.hr.front.service.process.WfFileService;
import com.auxgroup.hr.front.service.process.WfWkotHdrService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author lvliuhao
 * @version 创建时间：2018年7月20日 下午4:55:28
 * 类说明
 */
@Service("wfWkotHdrService")
public class WfWkotHdrServiceImpl implements WfWkotHdrService {
    private static final Logger logger = LoggerFactory.getLogger(WfWkotHdrServiceImpl.class);

    @Autowired
    private PsCWfWkotHdrRepository psCWfWkotHdrRepository;

    @Autowired
    private WfFileService wfFileService;

    @Autowired
    private WfInitServiceImpl wfInitService;

    @Resource(name = "dozerMapper")
    protected IObjectMapper objectMapper;

    @Autowired
    private PsCWfEmpVwRepository psCWfEmpVwRepository;
    @Autowired
    private PsCWfWkotDtlRepository psCWfWkotDtlRepository;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    protected SysDictService sysDictService;

    @Value("${auxgroup.hr.business.procUrl}")
    private String procUrl;

    @Override
    public List<PsCWfWkotDtl> queryByNbr(String cTransactionNbr) {
        return psCWfWkotDtlRepository.findByCTransactionNbr(cTransactionNbr);
    }

    @Override
    public PsCWfWkotHdr getWfInfo(String transNum) {
        return psCWfWkotHdrRepository.findOne(transNum);
    }

    @Override
    public void delWfInfo(String transNum) {
        wfFileService.delWfFiles(transNum, true);
        psCWfWkotHdrRepository.deleteByTransNum(transNum);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PsCWfWkotHdr saveWfInfo(PsCWfWkotHdr wkot, UserDTO user) {
        logger.info("save Wkot HdrInfo start:", wkot);
        PsCWfWkotHdr wkotHdr = psCWfWkotHdrRepository.findOne(wkot.getcTransactionNbr());
        if (wkotHdr == null) {
            String valideStr = valide(wkot, user);
            if (!"success".equals(valideStr)) {
                logger.info("HR 校验不通过", wkot);
                throw new ValidationException("", valideStr);
            }

            logger.info("no wkot for " + wkot.getcTransactionNbr());
            //FIXME 当前只处理自己提交的加班
            JobCurrPrimary primary = new JobCurrPrimary();
            primary.setEmplid(user.getEmplId());
            primary.setEmplRcd(new BigDecimal(0));
            PsCWfEmpVw vw = psCWfEmpVwRepository.findOne(primary);
            wkotHdr = objectMapper.map(vw, PsCWfWkotHdr.class);


            //FIXME 单个子表处理
            wkotHdr = wfInitService.init(wkotHdr, user, wkot.getcTransactionNbr());
            PsCWfWkotDtl dtl = new PsCWfWkotDtl();
            dtl.setEmplid(wkotHdr.getEmplid());
            dtl.setcJobLevel(vw.getcJobLevel());
            dtl.setcTransactionNbr(wkotHdr.getcTransactionNbr());
            dtl.setDeptid(vw.getDeptid());
            dtl.setName(vw.getNameDisplay());
            dtl.setRsFullName(vw.getRsFullName());
            psCWfWkotDtlRepository.save(dtl);
//			wkotHdr.setcOtherExplain(wkot.getcApplInfo());
        }
        wkotHdr.baseInit(wkot);

        //TODO 自己为自己申请提交，是否需要填充其它字段
        wkot.setEmplid(user.getEmplId());
        ObjectFieldUtils.handleNullValue(wkotHdr);
        return psCWfWkotHdrRepository.save(wkotHdr);
    }


    private String valide(PsCWfWkotHdr wkot, UserDTO user) {
        AuxCheckRequest valReq = new AuxCheckRequest("udp_AuxJBCheck");
        valReq.add("EmpNo", user.getEmplId());

        valReq.add("BDateTime", DateUtils.format(wkot.getDate1(), "yyyy-MM-dd") + wkot.getcHour().replace('A', ':') + " " + wkot.getcMinute2())
                .add("EDateTime", DateUtils.format(wkot.getDate2(), "yyyy-MM-dd") + wkot.getcHour1().replace('A', ':') + " " + wkot.getcMinute3())

                .add("BillType", "调休加班")
                .add("IsResult", "N")
                .add("Reason", wkot.getcApplInfo())
                .add("Addday", DateUtils.format(new Date(), "yyyy-MM-dd"))
                .add("BillNo", "");//FIXME

        AuxCheckResponse resp = restTemplate.postForObject(procUrl, valReq, AuxCheckResponse.class);
        logger.info("HR 校验{}", JSON.toJSONString(resp));
        if (!resp.isChecked("@returnvalue", "成功")) {
            return resp.getValue("returnvalue");
        }
        if ("O".equals(wkot.getcCardType())) {
            valReq = new AuxCheckRequest("udp_AuxTripJBCheck")
                    .add("EmpNo", user.getEmplId())
                    .add("DjDate", DateUtils.format(wkot.getDate1(), "yyyy-MM-dd"));
            resp = restTemplate.postForObject(procUrl, valReq, AuxCheckResponse.class);
            logger.info("HR 校验{}", JSON.toJSONString(resp));
            if (!resp.isChecked("@returnvalue", "Y")) {
                return "没有外出记录，不能申请外出加班（无需打卡）";
            }
        }

        Calendar c = Calendar.getInstance();
        c.setTime(wkot.getDate1());
        c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), Integer.valueOf(wkot.getcHour().substring(1)), Integer.valueOf(wkot.getcMinute2()));
        Date startDate = c.getTime();

        c.setTime(wkot.getDate2());
        c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), Integer.valueOf(wkot.getcHour1().substring(1)), Integer.valueOf(wkot.getcMinute2()));
        Date endDate = c.getTime();
        long day = (endDate.getTime() - startDate.getTime()) * 10 / 1000 / 60 / 60 / 7;
        double outDay = (int) (day * 1.0 / 10);
        if (day % 10 >= 5) {
            outDay += 0.5;
        }
        Double processingDay = sysDictService.getProcessingOverTimeDays(user.getEmplId());

        double totalDays = outDay;
        if (processingDay != null) {
            totalDays += processingDay;
        }

        valReq = new AuxCheckRequest("udp_AuxTXJBDays")
                .add("EmpNo", user.getEmplId())
                .add("QJBDays", totalDays + "");
        //FIXME
        resp = restTemplate.postForObject(procUrl, valReq, AuxCheckResponse.class);
        logger.info("HR 校验{}", JSON.toJSONString(resp));
        if (!resp.isChecked("@returnvalue", "0")) {
            return "您最近加班过多，请注意休息！";
        }
        return "success";
    }


}
 